#
import smtplib
from email.utils import formataddr
from email.mime.text import MIMEText
from base.LoggerHandler import logger
from config import config

email_config = config["163_email"]


class SendEmail:
    def __init__(self, title, content, receiver):
        self.email_host = email_config["email_host"]            # 邮件服务器
        self.email_user = email_config["email_user"]            # 发件人邮箱
        self.email_password = email_config["email_password"]    # 授权码
        self.email_from_name = "Owner Work"                     # 自定义发件人名
        self.title = "Owner Work %s" % title                    # 邮件标题
        self.content = f"""
感谢您注册使用Owner Work 账号密码备忘平台，本平台免费、开源。\n
{content} \n
如有疑问，可发送邮件到 heliangyuan10@163.com，感谢您的支持。"""   # 邮件内容
        self.receiver = receiver                                # 收件邮箱

    def send_email(self):
        message = MIMEText(self.content, 'plain', 'utf-8')           # 内容, 格式, 编码
        message['From'] = formataddr(pair=(self.email_from_name, self.email_user))
        message['To'] = self.receiver
        message['Subject'] = self.title

        try:
            smtpObj = smtplib.SMTP_SSL(self.email_host, 465)                            # 启用SSL发信, 端口一般是465
            smtpObj.login(self.email_user, self.email_password)                         # 登录验证
            smtpObj.sendmail(self.email_user, [self.receiver], message.as_string())     # 发送
            logger.info(f"已向邮箱 {self.receiver} 发送邮件。")
            print(f"已向邮箱 {self.receiver} 发送邮件。")
        except smtplib.SMTPException as e:
            logger.error(e)
            print(e)


if __name__ == '__main__':
    title = "验证码"
    content = """本次验证码为："""
    receivers = "z1145058527@qq.com"  # 收件人
    send_email = SendEmail(title, content, receivers)
    send_email.send_email()


